import UserApi from "@/api/manage/user";
import { getToken, setToken } from "@/api/auth";

const user = {
  state: {
    token: getToken(),
    user: {
      info: null
    }
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
      setToken(token);
    },
    SET_USER: (state, user) => {
      state.user.info = user;
    }
  },

  actions: {
    Login({ commit }, password) {
      return new Promise((resolve, reject) => {
        UserApi.login(password)
          .then(res => {
            if (res.success) {
              commit("SET_TOKEN", res.obj);
              resolve(res);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    GetUser({ commit }) {
      return new Promise((resolve, reject) => {
        UserApi.get()
          .then(res => {
            commit("SET_USER", res.obj);
            if (res.obj.token) {
              commit("SET_TOKEN", res.obj.token);
            }
            resolve(res);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    Logout({ commit }) {
      return new Promise((resolve, reject) => {
        UserApi.logout()
          .then(() => {
            commit("SET_USER", null);
            commit("SET_TOKEN", "");
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    }
  }
};

export default user;
